package com.qyhl.webtv.basiclib.base;

import android.app.Application;
import android.os.Handler;
import android.os.Looper;
import android.os.RemoteException;
import android.util.Log;
import android.widget.Toast;

import com.alibaba.android.arouter.launcher.ARouter;
import com.amap.api.maps.MapsInitializer;
import com.baidu.mobstat.StatService;
import com.bumptech.glide.Glide;
import com.orhanobut.hawk.Hawk;
import com.orhanobut.hawk.NoEncryption;
import com.qyhl.webtv.basiclib.BuildConfig;
import com.qyhl.webtv.basiclib.R;
import com.qyhl.webtv.basiclib.utils.cockroach.Cockroach;
import com.qyhl.webtv.basiclib.utils.cockroach.ExceptionHandler;
import com.qyhl.webtv.basiclib.utils.fresco.FrescoImageUtil;
import com.qyhl.webtv.basiclib.utils.network.EasyHttp;
import com.uuzuche.lib_zxing.activity.ZXingLibrary;
import com.weavey.loading.lib.LoadingLayout;

/**
 * 初始化应用程序
 * 需要有限初始化的代码可以放在这里初始化
 * @author  helin
 * @date  2019年2月22日16:14:54
 *
 */
public abstract class BaseApplication extends Application {


    @Override
    public void onCreate() {
        super.onCreate();
        // 初始化路由框架
        initRouter();
        //初始化loadingLayout
        initLoadingLayout();
        //其他初始化
        initOther();
        //默认初始化网络框架
        EasyHttp.init(this);
        //初始化百度统计
        StatService.start(this);

        try {
            MapsInitializer.initialize(this);
            MapsInitializer.updatePrivacyShow(this, true, true);
            MapsInitializer.updatePrivacyAgree(this, true);
        } catch (RemoteException e) {
            e.printStackTrace();
        }

    }


    /**
     * 崩溃
     */
    private void installCockroach() {
        final Thread.UncaughtExceptionHandler sysExcepHandler = Thread.getDefaultUncaughtExceptionHandler();
        final Toast toast = Toast.makeText(this, "", Toast.LENGTH_SHORT);
        Cockroach.install(this, new ExceptionHandler() {
            @Override
            protected void onUncaughtExceptionHappened(Thread thread, Throwable throwable) {
                Log.e("AndroidRuntime", "--->onUncaughtExceptionHappened:" + thread + "<---", throwable);
                new Handler(Looper.getMainLooper()).post(new Runnable() {
                    @Override
                    public void run() {
                        toast.setText("捕获到异常");
//                        toast.show();
                    }
                });
            }

            @Override
            protected void onBandageExceptionHappened(Throwable throwable) {
                throwable.printStackTrace();//打印警告级别log，该throwable可能是最开始的bug导致的，无需关心
                toast.setText("Cockroach Worked");
//                toast.show();
            }

            @Override
            protected void onEnterSafeMode() {

            }

            @Override
            protected void onMayBeBlackScreen(Throwable e) {
                Thread thread = Looper.getMainLooper().getThread();
                Log.e("AndroidRuntime", "--->onUncaughtExceptionHappened:" + thread + "<---", e);
                //黑屏时建议直接杀死app
                sysExcepHandler.uncaughtException(thread, new RuntimeException("black screen"));
            }
        });

    }




    private void initOther() {
        ZXingLibrary.initDisplayOpinion(this);
        Hawk.init(this)
                //加密
                .setEncryption(new NoEncryption())
                .build();//数据库初始化
        FrescoImageUtil.init(this);
        FrescoImageUtil.create();
    }

    @Override
    public void onTrimMemory(int level) {
        super.onTrimMemory(level);
        if (level == TRIM_MEMORY_UI_HIDDEN) {
            Glide.get(this).clearMemory();
        }
        //交由Glide处内存
        Glide.get(this).onTrimMemory(level);
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
        //内存低的时候清理Glide缓存
        Glide.get(this).clearMemory();
    }

    /**
     * 初始化loadingLayout
     */
    private void initLoadingLayout() {
        //loadinglayout全局配置
        LoadingLayout.getConfig()
                .setAllPageBackgroundColor(R.color.white)
                .setErrorText("出错啦~请稍后重试！")
                .setEmptyText("抱歉，暂无数据")
                .setNoNetworkText("无网络连接，请检查您的网络···")
                .setErrorImage(R.drawable.error_content)
                .setEmptyImage(R.drawable.empty_content)
                .setNoNetworkImage(R.drawable.error_network)
                .setAllTipTextColor(R.color.base_global_gray_lv2)
                .setAllTipTextSize(14)
                .setReloadButtonText("点击重试~~")
                .setReloadButtonTextSize(14)
                .setReloadButtonTextColor(R.color.base_global_gray_lv2)
                .setReloadButtonWidthAndHeight(150, 40);
    }



    /**
     * 初始化路由框架
     */
    private void initRouter() {
        if (isDebug()) {
            // 打印日志
            ARouter.openLog();
            // 开启调试模式(如果在InstantRun模式下运行，必须开启调试模式！线上版本需要关闭,否则有安全风险)
            ARouter.openDebug();
        }
        // 尽可能早，推荐在Application中初始化
        ARouter.init(this);
    }

    private boolean isDebug() {
        return BuildConfig.DEBUG;
    }
    /**
     * Application 初始化
     */
    public abstract void initModuleApp(Application application);

    /**
     * 所有 Application 初始化后的自定义操作
     */
    public abstract void initModuleData(Application application);

}
